const tencentcloud = require('tencentcloud-sdk-nodejs');

module.exports = class extends require('egg').Service {
  /** 校验验证码 */
  async check({ tel, sms }) {
    const { ctx } = this;

    const res = await ctx.helper.query({
      query: `SELECT sms FROM "meet_sms" WHERE tel = '${tel}' and create_time > '${ctx.helper.formatTime(
        Date.now() - 5 * 60 * 1000
      )}' ORDER BY create_time DESC`,
      find: true
    });

    if (!res || sms !== res.sms) {
      ctx.throw(400, '验证码错误');
    }
  }
  /** 发送短信验证码 */
  async create({ tel }) {
    const { ctx } = this;

    await this.isFrequent(tel);
    const sms = ctx.helper.random(1000, 9999);
    await this.sendSMS(tel, sms);

    const res = await ctx.helper.query({
      query: `INSERT INTO "meet_sms" ( tel, sms, create_time ) VALUES ( '${tel}', '${sms}', '${ctx.helper.formatTime()}' )`
    });

    return res;
  }
  /** 检查发送间隔是否太短 */
  async isFrequent(tel) {
    const { ctx } = this;

    const time = 60;
    const res = await ctx.helper.query({
      query: `SELECT * FROM "meet_sms" WHERE tel = '${tel}' and create_time > '${ctx.helper.formatTime(Date.now() - time * 1000)}'`
    });
    if (res.length) ctx.throw(400, '发送太频繁，请稍后再试');
  }
  /** 真实发送短信验证码 */
  async sendSMS(tel, sms) {
    const { config } = this;
    const clientConfig = {
      credential: {
        secretId: config.tencentCloud.secretId,
        secretKey: config.tencentCloud.secretKey
      },
      region: 'ap-guangzhou',
      profile: {
        httpProfile: {
          endpoint: 'sms.tencentcloudapi.com'
        }
      }
    };

    const SmsClient = tencentcloud.sms.v20210111.Client;

    const client = new SmsClient(clientConfig);
    const params = {
      PhoneNumberSet: ['86' + tel],
      SmsSdkAppId: '1400531823',
      SignName: '开宗源泉',
      TemplateId: '985202',
      TemplateParamSet: [String(sms), '3']
    };
    return await client.SendSms(params);
  }
};
